using System;
using FlowCanvas;
using FlowCanvas.Nodes;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI;
using Yoozoo.Gameplay.Liberty.AI.Node;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    public class TriggerNpcBehavior : CallableActionNodeBase
    {

        public static Action<int, Vector3> OnReachedEventPos;

        private FlowOutput onReachPos;

        private int uniqueId;
        private Vector3 eventPosition;
        
        protected override void OnRegisterPorts(FlowNode node)
        {
            var o = node.AddFlowOutput("In");
            var p1 = node.AddValueInput<int>("uniqueNpcId");
            var p2 = node.AddValueInput<string>("actionValue");
            var p3 = node.AddValueInput<string>("eventPointName");

            onReachPos = node.AddFlowOutput("onReachEventPos");
            
            node.AddFlowInput("Out", (Flow f) =>
            {
                Vector3 pos = Vector3.zero;
                AIEntity aiEntity = LibertyAIUtils.AIManager.NpcBirthManager.GetNpc(p1.value);
                if (!string.IsNullOrEmpty(p3.value.Trim()))
                {
                    var point = BlueprintUtils.GetBlueprintPoint(p3.value.Trim());
                    if (aiEntity!=null && point!=null)
                    {
                        aiEntity.data.eventPosition = point.position;
                        pos = point.position;
                    }
                }
                
                
                Invoke(p1.value, p2.value,pos); o.Call(f);
            });
        }

        private void Invoke(int uniqueNpcId, string actionValue,Vector3 pos)
        {
            uniqueId = uniqueNpcId;
            eventPosition = pos;
            
            OnReachedEventPos -= ReachedEventPos;
            OnReachedEventPos += ReachedEventPos;
            HasTriggerNpcBehavior.OnTriggerNpcBehavior?.Invoke(uniqueNpcId,actionValue);
        }

        private void ReachedEventPos(int uniqueNpcId, Vector3 eventPos)
        {
            if (uniqueNpcId == uniqueId && eventPos == eventPosition)
            {
                OnReachedEventPos -= ReachedEventPos;
                onReachPos?.Call(new Flow());
            }
        }
    }
}